#include "integrationtest.h"

IntegrationTest::IntegrationTest()
{
}

void IntegrationTest::initTestCase()
{
    logService = new LogService;
    serverMultithread = new ServerMultithread(logService, 0);
    QFile::remove("logs.txt");
}

void IntegrationTest::integrationTest()
{
    QVERIFY(serverMultithread->listen());

    QTcpSocket socket;
    socket.connectToHost("localhost", serverMultithread->serverPort());
    QVERIFY(socket.waitForConnected());

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);

    out << quint16(0) << QString("LOG") << QString("My log test!");
    out.device()->seek(0);
    out << quint16(block.size() - sizeof(quint16));

    QCOMPARE(socket.write(block), qint64(block.size()));

    QTest::qWait(1000);

    QVERIFY(QFile::exists("logs.txt"));

    QFile logs("logs.txt");
    QVERIFY(logs.open(QFile::ReadOnly));

    QDataStream in(&logs);
    QString result;
    in >> result;

    QCOMPARE(result, QString("My log test!"));

    logs.close();

    socket.disconnectFromHost();

    if(socket.state() != QAbstractSocket::UnconnectedState)
    {
        QVERIFY(socket.waitForDisconnected());
    }
}

void IntegrationTest::cleanupTestCase()
{
    delete logService;
    delete serverMultithread;
}
